package ext.vpde.cadvaulting.globalvault;

import java.util.*;

import wt.epm.EPMDocument;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import ext.vpde.cadvaulting.migration.*;
import ext.vpde.cadvaulting.util.ReleaseDrawing;
import ext.vpde.cadvaulting.util.SJTCSQL;

public class FindReleasedENs {

	public static void main ( String [] args ) throws Exception {
		if (args.length == 3) {
			if (LoadUtil.loginRemote(args[0],args[1])) {
				readEntries(args[2]);
			}
		}
		else System.out.println("\nUsage: java.ext.vpde.cadvaulting.FindReleasedENs userid userpw dateString");
    }
	
	private static void readEntries(String dateStr) throws Exception {
		System.out.println("BEGIN FIND RELEASED ENs: " + Calendar.getInstance().getTime());
		Hashtable ht = SJTCSQL.getEN(dateStr);
		processReleasedEN(ht);
		System.out.println("-END- FIND RELEASED ENs: " + Calendar.getInstance().getTime());
	}
	
	public static boolean checkReleasedEN(String itemNumber)throws Exception {
		boolean isReleased = false;
		//isReleased = (GVSQL.checkIfReleased(itemNumber)) ? true : false;
		return isReleased;
	}
	
	public static void processReleasedEN(Hashtable ht) {
		Enumeration hashEnum = ht.elements();
		while (hashEnum.hasMoreElements()) {
			StringTokenizer strTok = new StringTokenizer(hashEnum.nextElement().toString(),"|");
			String itemNumber = strTok.nextToken() + ".drw";
			String revision   = strTok.nextToken();
			String item_type  = strTok.nextToken();
			String enNumber   = strTok.nextToken();
			String relDate    = strTok.nextToken();
			String itemName   = strTok.nextToken();
			String thisDate   = strTok.nextToken();
			//System.out.println(itemNumber + " " + revision);
			
			try {
				QuerySpec qs   = new QuerySpec(EPMDocument.class);
				qs.appendWhere(new SearchCondition(EPMDocument.class,"master>CADName",  "=", itemNumber));
				qs.appendAnd();
				qs.appendWhere(new SearchCondition(EPMDocument.class,"versionInfo.identifier.versionId",  "=", revision));
				qs.appendOrderBy(EPMDocument.class,"thePersistInfo.theObjectIdentifier.id",true);
				QueryResult qr = PersistenceHelper.manager.find(qs);
				while (qr.hasMoreElements()) {
					EPMDocument thisDoc = (EPMDocument)qr.nextElement();
					if (thisDoc.isLatestIteration()) {
						System.out.println("FOUND: " + itemNumber + " " + revision);
						ReleaseDrawing.findRelatedDocuments(thisDoc);
					}
					
				}
			} catch (Exception e) { System.out.println(e.getLocalizedMessage());}
		}
	}
}